const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';

function Promisee(executor){
    this.callback = [];
    this.state = PENDING;
    this.result = undefined;
    const _onChange = function (state,value){
        if(this.state !== PENDING) return;
        this.state = state;
        this.result = value;
        this.callback.forEach(item=>{
            if(state===FULFILLED) item.onResolved();
            else if(state===REJECTED) item.onRejected();
        })

    }
    try {
        executor(_onChange.bind(this,FULFILLED),_onChange.bind(this,REJECTED))
    }catch(err){
        _onChange.call(this,REJECTED,err)
    }

}


Object.assign(Promisee.prototype,{
    // onResolved:成功回调
    // onRejected:失败回调
    then(onResolved,onRejected){
        return new Promisee((resolve,reject)=>{
            const _common = function (callback){
                setTimeout(()=>{
                    try{
                        const value = callback(this.result);
                        if(value instanceof Promisee){
                            value.then(resolve,reject);
                        }else {
                            resolve(value);
                        }
                    }catch (err){
                        reject(err);
                    }

                })
            }
            if(this.state === FULFILLED){
                _common.call(this,onResolved);
            }else if(this.state === REJECTED) {
                _common.call(this,onRejected);
            }else {
                this.callback.push({
                    onResolved : _common.bind(this,onResolved),
                    onRejected : _common.bind(this,onRejected)
                })
            }
        })
    },
    catch(){

    }
})



export default Promisee;

